package com.zhongxi.guoyuan.view.seller;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.seller.SellerCoinOrderAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.seller.BossSilverDetailResult;
import com.zhongxi.guoyuan.entity.seller.BossSilverResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ManagerCoinSellerActivity extends BaseActivity implements View.OnClickListener, PullToRefreshBase.OnRefreshListener2<ListView> {

    private PullToRefreshListView lvList;
    private List<BossSilverDetailResult.BossSilverDetailData> data = new ArrayList<>();
    private TextView tvStartTime;
    private TextView tvEndTime;
    private DatePickerDialog dialog;
    private SellerCoinOrderAdapter adapter;
    private String type;
    private TextView tvAllCoin;
    private TextView tvToday;
    private Map<String, String> map = new HashMap<>();
    private String endTime;
    private String startTime;
    private EditText etShop;
    private EditText etPhone;
    private ImageView ivSearch;
    private TextView tvCoin;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_manager_coin_seller);
        initTitle();
        tvTitle.setText("总管观察:银币商家");
        lvList = (PullToRefreshListView) findViewById(R.id.lvList);
        tvStartTime = (TextView) findViewById(R.id.tvStartTime);
        tvEndTime = (TextView) findViewById(R.id.tvEndTime);

        tvAllCoin = (TextView) findViewById(R.id.tvAllCoin);
        tvToday = (TextView) findViewById(R.id.tvTodayCoin);
        etShop = (EditText) findViewById(R.id.etShop);
        etPhone = (EditText) findViewById(R.id.etPhone);
        ivSearch = (ImageView) findViewById(R.id.ivSearch);
        tvCoin = (TextView) findViewById(R.id.tvCoin);
    }

    @Override
    protected void initData() {
        super.initData();
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateNowStr = sdf.format(now);
        tvStartTime.setText(dateNowStr);
        tvEndTime.setText(dateNowStr);
        startTime = endTime = dateNowStr;
        adapter = new SellerCoinOrderAdapter(context, data);
        lvList.setAdapter(adapter);

        type = "bosssilver";
        getServer(Url.BOSS_SILVER_MALL, null, "", true, null, "get");
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try{
            if("bosssilver".equals(type)){
                BossSilverResult result = gson.fromJson(response, BossSilverResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                if(null!=result.getAllEarnings()&&!"".equals(result.getAllEarnings())){
                    tvAllCoin.setText(result.getAllEarnings()+"银币");
                }else{
                    tvAllCoin.setText("*银币");
                }
                if(null!=result.getTodayEarnings()&&!"".equals(result.getTodayEarnings())){
                    tvToday.setText(result.getTodayEarnings()+"银币");
                }else{
                    tvToday.setText("*银币");
                }
                getDetails();
            }else if("bosssilverdetails".equals(type)){
                BossSilverDetailResult result = gson.fromJson(response, BossSilverDetailResult.class);
                if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj()))
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                if(null!=result.getSilverNum()&&!"".equals(result.getSilverNum())){
                    tvCoin.setText(result.getSilverNum()+"银币");
                }else{
                    tvCoin.setText("*银币");
                }
                if(pageNum==1){
                    data.clear();
                }
                if(result.getData().size()>0){
                    data.addAll(result.getData());
                }
                adapter.notifyDataSetChanged();
                lvList.onRefreshComplete();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try{
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj()))
            MyApplication.getInstance().setSpValue(result.getSafeobj());
            if(result.getCode()==9002){
                SharedPreferences sharedPrefrences = getSharedPreferences(Url.APP_SP, MODE_PRIVATE);
                sharedPrefrences.edit().putString("credentials", "").commit();
                showShortToast("用户登录已失效，请重新登录");
                startAct(SellerManagerLoginActivity.class);
                finish();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void getDetails() {
        if(CommonTool.TimeCompare(startTime, endTime)){
            type = "bosssilverdetails";
            map.clear();
            map.put("stime", startTime);
            map.put("etime", endTime);
            map.put("shopid", etShop.getText().toString().trim());
            map.put("userphone", etPhone.getText().toString().trim());
            String str = "&page="+pageNum;
            getServer(Url.BOSS_SILVER_DETAILS, map, str, true, null, "post");
        }else {
            showShortToast("结束时间不能小于开始时间");
        }
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        tvStartTime.setOnClickListener(this);
        tvEndTime.setOnClickListener(this);
        lvList.setOnRefreshListener(this);
        ivSearch.setOnClickListener(this);
    }

//    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ivBack:
                finish();
                break;
            case R.id.tvStartTime:
                showDateDialog(0);
                break;
            case R.id.tvEndTime:
                showDateDialog(1);
                break;
            case R.id.ivSearch:
                if(TextUtils.isEmpty(etPhone.getText().toString().trim())){
                    showShortToast("手机号不能为空");
                }else if(TextUtils.isEmpty(etShop.getText().toString().trim())){
                    showShortToast("店铺id不能为空");
                }else{
                    getDetails();
                }
                break;
        }
    }

    private void showDateDialog(final int index) {
        Calendar c = Calendar.getInstance();
        dialog = new DatePickerDialog(this, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                pageNum = 1;
                String mon = month+1+"";
                String text = year + "-" + mon + "-" + dayOfMonth;
                if(index == 0){
                    tvStartTime.setText(text);
                    startTime = text;
                }else if(index == 1){
                    tvEndTime.setText(text);
                    endTime = text;
                }
                getDetails();
            }
        }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
        dialog.setTitle("请选择时间：");
        dialog.getDatePicker().setCalendarViewShown(false);
        dialog.show();
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum = 1;
        getDetails();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum++;
        getDetails();
    }
}
